package com.jian.java.hello;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Jiange
 * @create 2021-07-28-11:19
 */
public class HelloServlet2 extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    /**
     * 在get请求时调用
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("获取请求的资源路径"+req.getRequestURI());//没有http://ip:port
        System.out.println("请求的URL");//有http://ip:port
        System.out.println("客户端的IP地址" + req.getRemoteAddr());
        System.out.println(req.getHeader("User-Agent"));
        System.out.println(req.getMethod());
        //获取请求参数
        req.setCharacterEncoding("utf-8");//解决中文乱码
        System.out.println(req.getParameter("name"));//获取get和post都能
        String[] hobbies = req.getParameterValues("hobby");

        /**
         * 请求转发必须要以 /  打头， /：地址表示http://ip:port/工程名
         * 服务端跳转
         * 浏览器的地址没有发生改变  是一次请求   共享req域中的数据  可以转发到web-inf文件夹
         * 只能访问自己工程的文件 会往后面加
         */
        RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-ING/web.xml");
        dispatcher.forward(req,resp);

        //客户端跳转
        resp.sendRedirect("www.baidu.com");

        //只能在字符流和字节流中选一个使用get  都用了会报错
        PrintWriter writer = resp.getWriter();
        writer.write("adsadsa");
        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write("adsadas".getBytes());
    }

    /**
     * post时调用
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
